//
//  MNDResetGestureViewController.m
//  minidai
//
//  Created by Vitas on 2018/5/31.
//  Copyright © 2018年 迷你金服. All rights reserved.
//

#import "MNDResetGestureViewController.h"
#import "GestureView.h"
#import "CALayer+Shake.h"

//顶部手势图与提示label间距
#define TopGestureViewMargin 20
//顶部宽高
#define TopViewWH 60

@interface MNDResetGestureViewController ()<GestureViewDelegate>

/* 手势view */
@property (strong, nonatomic) GestureView *gestureView;

@property (weak, nonatomic) IBOutlet UIButton *resetGestureButton;
@property(nonatomic, assign) BOOL isReset;
/* 密码状态 */
@property (strong, nonatomic) NSString *setGesture;

@property(nonatomic, strong) NSString *resetPassword;
@end

@implementation MNDResetGestureViewController

- (void)viewDidLoad {
    _isReset = YES;
    [super viewDidLoad];
    _gestureView.delegate = self;
    _setGesture = [UserDefaultsTool objectForKey:kGesturePassword];
    [self setupUI];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
}

//中途退出修改密码
- (void)backAction :(id)sender {

    if (self.setGesture.length > 0) {
        [UserDefaultsTool saveObject:self.setGesture forKey:kGesturePassword];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -搭建界面

- (void)setupUI {
    _topGestureView = [[TopGestureView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:_topGestureView];
    WeakSelf(self);
    
    [_topGestureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakself.view);
        make.bottom.equalTo(weakself.tipLabel.mas_top).mas_offset(-TopGestureViewMargin);
        make.width.height.mas_equalTo(TopViewWH);
    }];
}

//重新绘制事件
- (IBAction)clickResetAction:(UIButton *)sender {

    self.tipLabel.text = @"请绘制解锁图案";
    self.gestureView.resetPasswordStr = @"";
    //重新绘制密码
    self.gestureView.isReset = YES;
    self.resetGestureButton.hidden = YES;
    self.topLogImgV.hidden = YES;
    //顶部按钮归位
    for (UIButton *button in _topGestureView.selectBtnArr) {
        button.selected = NO;
        [button setBackgroundColor:[UIColor colorWithRed:210/255.0 green:218/255.0 blue:232/255.0 alpha:1.0]];
    }
}

#pragma mark -GestureViewDelegate
//设置密码
- (void)gestureLockSetPassword:(NSString *)password gestureView:(GestureView *)gestureView {
   NSString *gestureStr = [UserDefaultsTool objectForKey:kGesturePassword];
    if (gestureStr.length <= 0 || self.gestureView.isReset) {//如果还没有设置手势
        if(gestureView.selectBtnArr.count < 4) {
            _tipLabel.text = @"请设置至少4位手势密码";
            _tipLabel.textColor = [UIColor redColor];
            [_tipLabel.layer shake];
            return;
        } else {//设置密码，并且第二次设置
            _tipLabel.text = @"请再次绘制解锁图案";
            _tipLabel.textColor = [UIColor blackColor];
            _resetGestureButton.hidden = NO;
            //            _secondSet = YES;
            _resetPassword = password;
            self.gestureView.resetPasswordStr = password;
            self.gestureView.isReset = NO;
            for (int i = 0; i < password.length; i++) {
                NSString *select = [password substringWithRange:NSMakeRange(i, 1)];
                UIButton *selectBtn = [_topGestureView viewWithTag:select.intValue];
                selectBtn.selected = YES;
                if (selectBtn.selected == YES) {
                    [selectBtn setBackgroundColor:[UIColor colorWithRed:71/255.0 green:176/255.0 blue:236/255.0 alpha:1.0]];
                }
                //记录保存
                [_topGestureView.selectBtnArr  addObject:selectBtn];
            }
        }
    } else {//修改密码
        //重置密码为空
        
    }
}

//密码正确
- (void)gestureLockPasswordRight:(GestureView *)gestureView {
   
    //判断是关闭手势还是设置手势
    if (self.isReset) {
        self.tipLabel.text = @"请绘制解锁图案";
        self.gestureView.isReset = YES;
        self.topGestureView.hidden = NO;
        self.topLogImgV.hidden = YES;
        _isReset = NO;
    }else {
        //重置错误的次数
        NSString *erroCount = @"5";
        [UserDefaultsTool saveObject:erroCount forKey:kErrorCount];
        [gestureView savePassword:_resetPassword];
        [NetworkProgressHUD showHudMsg:@"手势密码修改成功"];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//密码错误
- (void)gestureLockPasswordError:(GestureView *)gestureView {
    //    gestureView.passwordError = YES;
    if (_setGesture==nil) {
        _tipLabel.text = @"密码不一致";
        _tipLabel.textColor = [UIColor redColor];
    } else {
        _tipLabel.text = [NSString stringWithFormat:@"手势密码错误"];
        _tipLabel.textColor = [UIColor redColor];
        [_tipLabel.layer shake];
    }
}

#pragma mark -点击事件
//忘记手势密码点击事件

- (IBAction)forgetGestureAction:(UIButton *)sender {
    //提示label
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"忘记手势密码，需要重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    //取消
    UIAlertAction *setNetworkAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    WeakSelf(self);
    //设置
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //登出
        [NetworkProgressHUD showHud];
        NSString *param = [MNDSign signParamWithObj:nil];
        [APIManager sendRequestWithPath:API_USER_LOGOUT parameters:@{@"param": param} method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
            
            [NetworkProgressHUD hideHud];
            if (responseModel.error) {
                
                return;
            }
            //清空用户数据
            [MNDLoginUserModel deleteAllUserDatas];
            //清空保存的手势密码及次数要求
            [UserDefaultsTool saveObject:nil forKey:kGesturePassword];
            [UserDefaultsTool saveObject:@"5" forKey:kErrorCount];
            [UserDefaultsTool saveObject:nil forKey:kFingerPassword];
            
            [UserDefaultsTool saveObject:@"YES" forKey:kForgetGesture];
            
            [weakself dismissViewControllerAnimated:YES completion:^{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"dismissFingerVC" object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"popToRootViewControllerNotification" object:nil];
            }];
            [weakself.navigationController popToRootViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"popToRootViewControllerNotification" object:nil];
        } onFailure:^(NSError *error) {
            [NetworkProgressHUD hideHud];
        }];
    }];
    
    //添加到控制器
    [alertController addAction:setNetworkAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
